﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StockTrading.Model;
using StockTrading.Triggers;
using StockTrading.View;
using StockTrading.View.Pages;
using StockTrading.ViewModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace StockTrading
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public static ServiceProvider serviceProvider;
        #region Ctor
        public App()
        {
            ServiceCollection services = new ServiceCollection();
            ConfigureServices(services);
            serviceProvider = services.BuildServiceProvider();
        }
        #endregion
        #region Method
        private void ConfigureServices(ServiceCollection services)
        {
            object instance = GetApplicationDbContext();
            //Services Configuration
            //注册对象到容器中
            services.AddSingleton (typeof(ApplicationDbContext), instance);

            services.AddSingleton<LoginViewModel>();

            services.AddSingleton<MainViewModel>();
            services.AddSingleton<StockViewModel>();

            services.AddSingleton<SignInView>();
            //注册View
            services.AddSingleton<MainView>();
            services.AddSingleton<StockView>();
            //注册ViewModel

            services.AddSingleton<StockDetails>();
            services.AddSingleton<StockDetailsViewModel>();
            services.AddSingleton<Info>();
            services.AddSingleton<Cooporation>();
            services.AddSingleton<Help>();
            services.AddSingleton<StockView>();
            services.AddSingleton<Trade>();
        }
        private object GetApplicationDbContext()
        {
            //从配置文件中获取用户选择的数据库服务器
            var serverchoice = ConfigurationManager.AppSettings.Get("ServerNode");
            if (serverchoice == null)
            {
                MessageBox.Show("未找到ServerNode项，配置文件丢失");
                Environment.Exit(1);
            }

            //实例化配置文件对应类型
            var dbtype = Type.GetType(serverchoice);

            if (dbtype == null)
            {
                MessageBox.Show("选择的数据库暂未支持");
                Environment.Exit(1);
            }

            object instance = null;
            //使用给定类型实例化类
            try
            {
                instance = Activator.CreateInstance(dbtype);
            }
            catch
            {
                MessageBox.Show("数据库上下文创建失败");
                Environment.Exit(1);
            };
            return instance;
        }
        private void OnStartup(object sender, StartupEventArgs e)
        {

            var mainWindow = serviceProvider.GetService<MainView>();
            mainWindow.Show();
        }
        #endregion
    }
}
